package pay.utils;


import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * 文件加密相关
 */
public class MD5Util {

    protected static char hex[] = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    protected static MessageDigest messagedigest = null;

    static {
        try {

            //得到MD5实例
            messagedigest = MessageDigest.getInstance("MD5");

        } catch (Exception e) {

        }

    }

    public static String getFileMD5String(File file) throws IOException {
        FileInputStream in = new FileInputStream(file);

        FileChannel ch = in.getChannel();

        MappedByteBuffer byteBuffer =

                ch.map(FileChannel.MapMode.READ_ONLY, 0,

                        file.length());

        messagedigest.update(byteBuffer);

        return bufferToHex(messagedigest.digest());
    }

    //图片到byte数组
    public static byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        System.out.println("data = " + data.length);
        return data;
    }

    private static String bufferToHex(byte bytes[]) {

        return bufferToHex(bytes, 0, bytes.length);

    }

    private static String bufferToHex(byte bytes[], int m, int n) {

        StringBuffer stringbuffer = new StringBuffer(2 * n);

        int k = m + n;

        for (int l = m; l < k; l++) {

            appendHexPair(bytes[l], stringbuffer);

        }

        return stringbuffer.toString();

    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {

        char c0 = hex[(bt & 0xf0) >> 4];

        char c1 = hex[bt & 0xf];

        stringbuffer.append(c0);

        stringbuffer.append(c1);

    }

    public static void main(String[] args) throws Exception {
        String filemd5str = MD5Util.getFileMD5String(new File("99999.jpg"));

        System.out.println("filemd5str =" + filemd5str);
    }
}
